package com.sundaying.gooway.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.sundaying.gooway.dao.UserDao;
import com.sundaying.gooway.entity.User;

/**
 * 用户管理类
 * 
 * @author liuhja
 * 
 */
@Component("userService")
public class UserService {
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	@Resource(name = "userDao")
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 添加新用户
	 * 
	 * @param user
	 *            新用户
	 * @return 添加操作的结果。1表示成功，0表示失败
	 */
	public int add(User user) {
		if ("".equals(user.getUserName())) {
			return 0;
		}

		userDao.save(user);
		return 1;
	}

	/**
	 * 用户登录系统
	 * 
	 * @param user
	 *            用户登录信息
	 * @return 是否登录成功
	 */
	public int login(User user) {
		int result = 0;
		String hql = "from User user where user.username=?";
		List<Object> param = new ArrayList<Object>();
		param.add(user.getUserName());
			
		List<User> userList = userDao.list(hql, param);
		if(userList.size()==0)
			return 0;
		
		// 要使用equqls，而不是使用==
		if (((User)userList.get(0)).getPassword().equals(user.getPassword()))
			result = 1;
		return result;
	}

	/**
	 * 获取所有用户
	 * 
	 * @return 所有用户列表List
	 */
	public List<User> list() {
		List<User> userList = userDao.list();
		return userList;
	}
	
	public int update(User user){
		int result = 0;
		result = userDao.update(user);
		return result;
	}
	
	public int delete(int id){
		int result = 0;
		result = userDao.delete(userDao.load(id));
		return result;
	}
}
